package link.ahsj.xssdemo.config;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.DispatcherType;

/**
 * @Author Eastern unbeaten
 * @Email chenshiyun2011@163.com 
 * @Date 2020/3/1 12:33 上午
 */
@Configuration
public class SysMvcConfig implements WebMvcConfigurer {

    //忽略bean创建细节拉
    SysConfigServer sysConfigServer = new SysConfigServer();


    /**
     * xssFilter注册
     */
    @Bean
    public FilterRegistrationBean xssFilterRegistration() {
        //开启动态的xss开关
        XssFilter xssFilter = new XssFilter(() -> sysConfigServer.getEnabled());
        FilterRegistrationBean registration = new FilterRegistrationBean(xssFilter);
        registration.setDispatcherTypes(DispatcherType.REQUEST);
        registration.setOrder(Ordered.LOWEST_PRECEDENCE);
        registration.addUrlPatterns("/*");
        return registration;
    }

    /**
     * 解决跨域问题
     **/
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedHeaders("*")
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS");
    }
}
